package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String subFileName = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString()+subFileName;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String formatDate = sdf.format(new Date());

        String fileUrl =  formatDate+uuid;


        File file1 = new File(path+formatDate);
        file1.mkdirs();

        file.transferTo(new File(path+fileUrl));

        return R.success(fileUrl);

    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        FileInputStream fis = new FileInputStream(new File(path+name));
        ServletOutputStream outputStream = response.getOutputStream();
        int len;
        byte[] lens = new byte[1024];
        while((len=fis.read(lens))!=-1){
            outputStream.write(lens,0,len);
            outputStream.flush();
        }
        fis.close();
        outputStream.close();
    }
}
